<template>
  <div class="role-manager-container">
    <el-form
      ref="form"
      label-position="left"
      :model="roleManagerSearch"
      label-width="100px"
    >
      <el-row :gutter="15">
        <el-col :span="7">
          <el-form-item label="角色名称：">
            <el-input
              v-model.trim="roleManagerSearch.roleName"
              show-word-limit
              maxlength="30"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div style="position: relative;top: 5px;">
            <el-button
              type="primary"
              @click="queryMethods"
            >
              查询
            </el-button>
            <el-button
              type="primary"
              @click="addNewRoleMethods"
            >
              新增
            </el-button>
            <el-button
              type="danger"
              @click="showMutiDelConfirm"
            >
              批量删除
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <CommonTable
      ref="roleListRef"
      v-loading="isLoading"
      :is-selection="true"
      :is-show-index="false"
      :t-column-data="roleManagerCol"
      :t-data="roleManagerList"
      :is-has-opera="true"
      row-key="roleId"
      :is-reserve-select="true"
      @changeRow="changeSelectionList"
    >
      <template
        slot="operate"
        slot-scope="scope"
      >
        <div
          v-if="scope.row.roleId !== 1"
          class="do-list"
        >
          <span
            @click="getRoleDetailById(scope.row)"
          >编辑</span>
          <span
            @click="giveRoleAuth(scope.row)"
          >人员分配</span>

          <span
            class="del-button"
            @click="delRoleConfirm(scope.row)"
          >删除</span>
        </div>
      </template>
    </CommonTable>

    <el-pagination
      class="page-nation"
      :current-page="roleManagerSearch.page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="roleManagerSearch.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      :title="addRoleModel.roleId?'角色修改':'角色新增'"
      :visible.sync="isShowAddRole"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="roleModelForm"
        :rules="roleRules"
        :model="addRoleModel"
        label-width="80px"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input
            v-model.trim="addRoleModel.roleName"
            show-word-limit
            maxlength="30"
          />
        </el-form-item>
        <el-form-item
          label="角色权限"
          prop="menuIds"
        >
          <el-tree
            ref="menuTree"
            :data="treeData"
            show-checkbox
            node-key="id"
            :default-expanded-keys="hasCheckedTree"
            :check-strictly="ischeckStrictly"
            :props="defaultProps"
            @check-change="changeRoleAuth"
          />
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
        >
          <el-input
            v-model.trim="addRoleModel.roleDesc"
            show-word-limit
            maxlength="30"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          type="primary"
          @click="addNewRole"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!--人员分配-->
    <el-dialog
      title="人员分配"
      :visible.sync="isShowGiveRoleAuth"
      width="70%"
      :before-close="handleClose"
    >
      <div class="give-role-auth-container">
        <div>
          <div class="give-title">
            可选列表
          </div>
          <el-input
            v-model="searchCanSelect"
            placeholder="请输入内容"
            suffix-icon="el-icon-search"
            @input="changeSearchCanSelect"
          />
          <el-table
            ref="multipleTable"
            border
            class="selection-table"
            :data="unallocatedDataList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleCanSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              prop="nickName"
              label="姓名"
              width="120"
            />
            <el-table-column
              prop="userName"
              label="用户名"
              width="120"
            />
            <el-table-column
              prop="phone"
              label="手机号"
              width="120"
            />
          </el-table>
        </div>
        <div>
          <div
            class="icon-big el-icon-right"
            @click="changeClassToSelected('selected')"
          />
          <div
            class="icon-big el-icon-back"
            @click="changeClassToSelected('unSelect')"
          />
        </div>
        <div>
          <div class="give-title">
            已选列表
          </div>
          <el-input
            v-model="searchHasCanSelect"
            placeholder="请输入内容"
            suffix-icon="el-icon-search"
            @input="changeSearchHasSelect"
          />
          <el-table
            ref="multipleTable"
            border
            class="selection-table"
            :data="allocatedDataList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleHasSelectedChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              prop="nickName"
              label="姓名"
              width="120"
            />
            <el-table-column
              prop="userName"
              label="用户名"
              width="120"
            />
            <el-table-column
              prop="phone"
              label="手机号"
              width="120"
            />
          </el-table>
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmGiveRoleConfig"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!--删除提示-->
    <el-dialog
      title=""
      :visible.sync="warnningDialog"
      width="20%"
      :before-close="handleWarnClose"
      center
    >
      <div class="warn-container-box">
        <div class="flex-row">
          <div class="el-icon-warning-outline big-icon" />
          <div class="warn-words">
            删除提醒
          </div>
        </div>
        <div class="small-tips">
          此操作为不可逆，请谨慎处理!
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleWarnClose">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmDelMethods"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from '@/components/CommonTable/Table'
import { roleManagerCol } from './tableCol/roleManagerCol'
import * as service from './service'

export default {
  name: 'Role',
  data() {
    const validateTree = (rule, value, callback) => {
      const checkedTree = this.$refs.menuTree.getCheckedNodes()
      if (checkedTree.length === 0) {
        callback(new Error('请选择菜单'))
      } else {
        callback()
      }
    }
    return {
      ischeckStrictly: false,
      searchCanSelect: '',
      searchHasCanSelect: '',
      isShowGiveRoleAuth: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      roleRules: {
        roleName: [
          { required: true, message: '请填写角色名称', trigger: 'change' }
        ],
        roleDesc: [
          { required: true, message: '请填写角色描述', trigger: 'change' }
        ],
        menuIds: [
          { required: true, validator: validateTree, trigger: 'change' }
        ]
      },
      hasCheckedTree: [],
      roleManagerList: [],
      addRoleModel: {
        menuIds: [],
        roleName: '',
        roleDesc: ''
      },
      roleManagerCol,
      roleManagerSearch: {
        roleName: '',
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      defaultCheckedTree: [],
      isShowAddRole: false,
      canSelectionList: [],
      hasSelectedList: [],
      isLoading: false,
      warnningDialog: false,
      clickRowCache: {},
      delRoleList: [],
      userInfo: {},
      unallocatedDataList: [],
      unallocatedDataListHistory: [],
      allocatedDataList: [],
      allocatedDataListHistory: [],
      clickRoleCache: {}
    }
  },
  component: {
    CommonTable
  },
  mounted() {
    this.userInfo = JSON.parse(window.localStorage.getItem('userInfo'))
    this.getMenuList()
    this.getRoleList()
  },
  methods: {
    confirmGiveRoleConfig() {
      const allocatedData = []
      this.allocatedDataList.forEach((item) => {
        allocatedData.push(item.userId)
      })
      const params = {
        roleId: this.clickRoleCache.roleId,
        userIds: allocatedData.join(',')
      }
      // if(params.userIds === '') {
      //   this.$message.error('请从可选列表选择一个到已选中')
      //   // this.handleClose()
      //   return
      // }

      service.meetingBatchAuth(params).then(() => {
        this.$message.success('分配成功')
        this.handleClose()
      })
    },
    changeClassToSelected(type) {
      if (type === 'selected') {
        this.allocatedDataList = new Set([...this.canSelectionList, ...this.allocatedDataList])
        this.allocatedDataList = [...this.allocatedDataList].slice()
        this.allocatedDataListHistory = [...this.allocatedDataList].slice()
        this.allocatedDataList.splice(0, 0)
        this.unallocatedDataList.splice(0, 0)

        // 删除选中数据
        this.canSelectionList.forEach((item) => {
          const findIndex = this.unallocatedDataList.findIndex((result) => {
            return result.userId === item.userId
          })
          if (findIndex !== -1) {
            this.unallocatedDataList.splice(findIndex, 1)
          }
        })
      }

      if(type === 'unSelect') {
        this.unallocatedDataList = new Set([...this.hasSelectedList, ...this.unallocatedDataList])
        this.unallocatedDataList = [...this.unallocatedDataList].slice()
        this.unallocatedDataList.splice(0, 0)
        this.allocatedDataList.splice(0, 0)

        this.unallocatedDataListHistory = [...this.unallocatedDataList].slice()
        // 删除选中数据
        this.hasSelectedList.forEach((item) => {
          const findIndex = this.allocatedDataList.findIndex((result) => {
            return result.userId === item.userId
          })
          if (findIndex !== -1) {
            this.allocatedDataList.splice(findIndex, 1)
          }
        })
      }
    },
    changeSearchHasSelect(val) {
      console.log('val ---', val)
      if (val === '') {
        this.allocatedDataList = this.allocatedDataListHistory.slice()
      } else {
        const tmpArr = []
        this.allocatedDataList.forEach((item) => {
          if (item.userName.indexOf(val) !== -1) {
            tmpArr.push(item)
          }
        })
        this.allocatedDataList = tmpArr.slice()
      }
    },
    changeSearchCanSelect(val) {
      if (val === '') {
        this.unallocatedDataList = this.unallocatedDataListHistory.slice()
      } else {
        const tmpArr = []
        this.unallocatedDataList.forEach((item) => {
          if (item.userName.indexOf(val) !== -1) {
            tmpArr.push(item)
          }
        })
        this.unallocatedDataList = tmpArr.slice()
      }
    },
    getUnAllocatedListMethods(roleId) {
      const params = {
        roleId: roleId
      }
      service.meetingUnallocatedList(params).then((res) => {
        this.unallocatedDataList = res.data.rows.slice()
        this.unallocatedDataListHistory = res.data.rows.slice()
      })
    },
    getAllocatedListMethods(roleId) {
      const params = {
        roleId: roleId
      }
      service.meetingAllocatedList(params).then((res) => {
        console.log('res.data ---', res)
        this.allocatedDataList = res.data.rows.slice()
        this.allocatedDataListHistory = res.data.rows.slice()
      })
    },
    changeRoleAuth() {
      this.$refs.roleModelForm.validate()
    },
    changeSelectionList(val) {
      this.delRoleList = val.slice()
    },
    confirmDelMethods() {
      const params = {
        roleIds: []
      }
      if (Object.keys(this.clickRowCache).length > 0) {
        params.roleIds = this.clickRowCache.roleId
      }

      if (this.delRoleList.length > 0) {
        const roleIdList = []
        this.delRoleList.forEach((item) => {
          roleIdList.push(item.roleId)
        })
        if (roleIdList.indexOf('1') !== -1) {
          this.$message.error('超级管理员不能删除啊')
          return
        }
        params.roleIds = roleIdList.join(',')
      }

      service.delMeetingRoleById(params).then(() => {
        this.$message.success('删除成功')
        this.roleManagerSearch.pageNum = 1
        this.handleWarnClose()
        this.getRoleList()
        this.delRoleList = []
        // 清空选中
        this.$refs.roleListRef.clearSelectionMethods()
      }).catch((err) => {

      })
    },
    handleWarnClose() {
      this.clickRowCache = {}
      this.warnningDialog = false
    },
    showMutiDelConfirm() {
      if (this.delRoleList.length === 0) {
        this.$message.error('请选择删除的角色')
        return
      }
      this.warnningDialog = true
    },
    delRoleConfirm(row) {
      this.clickRowCache = Object.assign({}, row)
      this.warnningDialog = true
    },
    queryMethods() {
      this.roleManagerSearch.page = 1
      this.getRoleList()
    },
    getRoleDetailById(row) {
      const params = {
        roleId: row.roleId
      }
      this.hasCheckedTree = []
      this.isLoading = true
      service.getMeetingRoleDetail(params).then((res) => {
        this.isLoading = false
        this.hasCheckedTree = res.data.menuIds.slice()
        this.ischeckStrictly = true
        this.$nextTick(() => {
          this.$refs.menuTree.setCheckedKeys(res.data.menuIds) //给树节点赋值
          this.ischeckStrictly = false
        })
        this.addRoleModel.roleName = res.data.roleName
        this.addRoleModel.roleDesc = res.data.roleDesc
        this.addRoleModel.roleId = res.data.roleId
        this.addRoleModel.menuIds = res.data.menuIds.slice()
        this.isShowAddRole = true
      })
    },
    addNewRole() {
      const checkedTree = this.$refs.menuTree.getCheckedNodes(false, true)
      const menuIds = []
      checkedTree.forEach((item) => {
        menuIds.push(item.id)
      })
      this.addRoleModel.menuIds = menuIds.slice()
      this.$refs.roleModelForm.validate((valid) => {
        if (valid) {
          const params = Object.assign({}, this.addRoleModel)

          if (this.addRoleModel.roleId) {
            params.roleId = this.addRoleModel.roleId
            this.isLoading = true
            service.editMeetingOldRole(params).then(() => {
              this.isLoading = false
              this.$message.success('编辑成功')
              this.getRoleList()
              this.handleClose()
            }).catch(() => {
              this.isLoading = false
            })
          } else {
            this.isLoading = true
            service.addMeetingNewRole(params).then(() => {
              this.isLoading = false
              this.$message.success('新增成功')
              this.getRoleList()
              this.handleClose()
            }).catch(() => {
              this.isLoading = false
            })
          }
        }
      })
    },
    getMenuList() {
      service.getMeetingMenuList({}).then((res) => {
        // 根据名称放菜单顺序
        // const menuSort = ['平台授权管理', '供应商管理', '用户管理', '任务管理', '数据字典', '基础信息', '轮播图管理', '新闻管理', '帮助中心', '财务中心', '消息中心']
        // let sortedMenuArr = []
        //
        // menuSort.forEach((item, key) => {
        //   const tmpMenu = res.data.filter((result) => {
        //     return result.label === item
        //   })
        //
        //   let tmpMenuCol = tmpMenu[0]
        //   if(item === '任务管理') {
        //     tmpMenuCol.children = tmpMenuCol.children.filter((result) => {
        //       return result.id != 26
        //     })
        //     tmpMenu[0].children = tmpMenuCol.children
        //   }
        //
        //   if (tmpMenu.length > 0) {
        //     sortedMenuArr.push(tmpMenu[0])
        //   }
        //   if (tmpMenu.length > 1) {
        //     this.$message.error('菜单配置重名, 影响排序请检查')
        //   }
        // })

        this.treeData = res.data.slice()
      })
    },
    getRoleList() {
      this.isLoading = true
      const params = Object.assign({}, this.roleManagerSearch)
      service.getMeetingRoleList(params).then((res) => {
        this.isLoading = false
        this.roleManagerList = res.data.rows
        this.total = res.data.total
      }).catch((res) => {
        this.isLoading = false
      })
    },
    giveRoleAuth(row) {
      this.clickRoleCache = Object.assign({}, row)
      this.getAllocatedListMethods(row.roleId)
      this.getUnAllocatedListMethods(row.roleId)
      this.isShowGiveRoleAuth = true
    },
    handleHasSelectedChange(val) {
      this.hasSelectedList = val.slice()
    },
    handleCanSelectionChange(val) {
      this.canSelectionList = val.slice()
    },
    handleClose() {
      // 清空选中节点
      this.searchCanSelect = ''
      this.searchHasCanSelect = ''
      if (this.$refs.menuTree) {
        this.$refs.menuTree.setCheckedKeys([])
      }
      this.isShowAddRole = false
      this.isShowGiveRoleAuth = false
      this.addRoleModel = Object.assign({}, {
        roleName: '',
        roleDesc: ''
      })
      this.clickRoleCache = {}
    },
    addNewRoleMethods() {
      this.isShowAddRole = true
      let defaultIds = [1, 2, 3]
      this.treeData.forEach((item) => {
        if(defaultIds.indexOf(item.id) !== -1) {
          item.disabled = true
        }
      })
      this.$nextTick(() => {
        this.$refs.menuTree.setCheckedKeys(defaultIds)
      })
    },
    handleSizeChange(size) {
      this.roleManagerSearch.pageSize = size
      this.getRoleList()
    },
    handleCurrentChange(page) {
      this.roleManagerSearch.pageNum = page
      this.getRoleList()
    }
  }
}
</script>

<style scoped lang="scss">
.give-title{
  margin-bottom: 15px;
}
.role-manager-container{
  padding: 15px;
  background-color: #fff;
}
.page-nation{
  margin-top: 15px;
  text-align: right;
}
.give-role-auth-container{
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.selection-table{
  margin-top: 15px;
}
.icon-big{
  display: block;
  font-size: 36px;
  cursor: pointer;
  position: relative;
  top: 79px;
}
.big-icon{
  font-size: 42px;
}
.flex-row{
  display: flex;
  align-items: center;
  font-size: 18px;
  justify-content: center;
}
.warn-container-box{
  text-align: center;
}
.warn-words{
  margin-left: 30px;
}
.small-tips{
  margin-top: 15px;
}
.do-list {
  span {
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
    color: #F56C6C;
    &.del-button{
      color: #F56C6C;
    }
  }
}
</style>
